process.stdout.setEncoding('utf-8');
const Excel = require('exceljs');

const fs = require('fs');
const path = require('path');

const fileUrl = './logs_10000';
createFolder(fileUrl);
const files = fs.readdirSync(fileUrl);
var exec = require("child_process").exec;
function runCmd(cmd) {
    return new Promise(function (resolve, reject) {
        exec(cmd, {
            maxBuffer: 1024 * 2000
        }, function (err, stdout, stderr) {
            if (err) {
                console.log(err);
                reject(err);
            } else if (stderr.lenght > 0) {
                reject(new Error(stderr.toString()));
            } else {
                console.log(stdout);
                resolve();
            }
        });
    });
};
// 时间格式化，1、2、3、4变成01、02、03、04
function doubleStr(number) {
    return number < 10 ? '0' + number : number
}
main();
async function main() {
    await runCmd(`for /f "delims=" %i in ('where flutter') do @cd /d "%~dpi" && git pull`);
    await runCmd(`cd ..\\automated_testing_demo && flutter test .\\integration_test\\path_provider_test_10000.dart --machine > ..\\node_test_server\\${fileUrl}\\path_provider_test.txt`);
    await runCmd(`cd ..\\automated_testing_demo && flutter test .\\integration_test\\key_input_test_10000.dart --machine > ..\\node_test_server\\${fileUrl}\\key_input_test.txt`);
    await runCmd(`cd ..\\automated_testing_demo && flutter test .\\integration_test\\sqflite_test_10000.dart --machine > ..\\node_test_server\\${fileUrl}\\sqflite_test.txt`);
    createXlsx();
}

function createFolder(dirName) {
    try {
        if (!fs.existsSync(path.resolve(__dirname, dirName))) {
            fs.mkdirSync(path.resolve(__dirname, dirName), { recursive: true });
        } else {
        }
    } catch (err) {
        console.error(err);
    }
}

// 生成表格
function createXlsx() {
    var time = new Date();
    var dirName = (time.getMonth() + 1) + '' + doubleStr(time.getDate());
    createFolder(dirName)
    const workbook = new Excel.Workbook();
    files.forEach(async item => {
        var fileStr = fs.readFileSync(fileUrl + '/' + item, 'utf8');
        const result = fomateTxt(fileStr)
        const sheet = workbook.addWorksheet(item);
        sheet.columns = [
            { header: '测试项', key: 'testName', width: 20 },
            { header: '结果', key: 'result', width: 10 },
            { header: '运行时间(ms)', key: 'difference', width: 10 },
            { header: '打印值', key: 'message', width: 50 },
            { header: '路径', key: 'testUrl', width: 50 },
        ];
        result.forEach(item => {
            sheet.addRow(item)
        })
        // 通过流发送文件
    })

    workbook.xlsx.writeFile(dirName + '/' + doubleStr(time.getHours()) + '-' + doubleStr(time.getMinutes()) + '.xlsx');
}
// 处理txt数据
function fomateTxt(data) {
    let result = [];
    let resultMap = new Map();
    data.split('\n').forEach(item => {
        if (/^\{.*\}$/.test(item)) {
            const itemJson = JSON.parse(item);
            if (itemJson.type === 'testStart') {
                resultMap.set(itemJson.test.id, { ...itemJson, messageList: [] });
            }
            if (itemJson.testID) {
                const newItem = resultMap.get(itemJson.testID);
                newItem.difference = itemJson.time - newItem.time
                if (itemJson.type === 'testDone') {
                    newItem.result = itemJson.result;
                } else if (itemJson.type === 'print') {
                    newItem.messageList.push(itemJson.message);
                }
                resultMap.set(itemJson.testID, newItem)
            }
        }
    })
    for (let [key, mapValue] of resultMap) {
        mapValue.testName = mapValue.test.name
        mapValue.testUrl = mapValue.test.url
        mapValue.message = mapValue.messageList.join('\n');
        result.push(mapValue);
    }
    return result;
}
